/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.songlanyun.modules.user.service.impl;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;

import com.songlanyun.common.utils.R;
import com.songlanyun.modules.user.dao.SysUserDao;
import com.songlanyun.modules.user.entity.SysUserEntity;

import com.songlanyun.modules.user.exception.UserException;
import com.songlanyun.modules.user.service.SysUserRoleService;
import com.songlanyun.modules.user.service.SysUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private SysUserRoleService sysUserRoleService;

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String username = MapUtil.getStr(params, "username");
        String createUserId = MapUtil.getStr(params, "createUserId");

        IPage<SysUserEntity> page = this.page(
                new Query<SysUserEntity>().getPage(params),
                new LambdaQueryWrapper<SysUserEntity>()
                        .eq(StringUtils.isNotBlank(createUserId), SysUserEntity::getCreateUserId, createUserId)
                        .like(StringUtils.isNotBlank(username), SysUserEntity::getUsername, username)
        );

        page.getRecords().forEach(SysUserEntity::loadRoleName);

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(SysUserEntity user) {

        user.passwordEn(user.getPassword());//密码加密
        this.save(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserEntity user) {
        if (StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
        }
        this.updateById(user);

        if (user.getRoleIdList() != null && user.getRoleIdList().size() > 0) {
            //保存用户与角色关系
            sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
        }

    }


    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        return this.baseMapper.updatePassword(userId, password, newPassword);
    }

    /**
     * 根据用户名，查询系统用户
     *
     * @param username
     * @return
     */
    @Override
    public SysUserEntity queryByUserName(String username) {
        return baseMapper.queryByUserName(username);
    }


    /**
     * 查询商家是否分配管理员账号
     *
     * @param
     * @return
     */
    @Override
    public SysUserEntity selectShopAdmin(Long shopId, boolean isThrow) {
        SysUserEntity sysUserEntity = baseMapper.selectShopAdmin(shopId);
        if (sysUserEntity == null) {
            if (isThrow) {
                throw new RRException(UserException.USER_NOT_EXISTS);
            }
        }
        return sysUserEntity;
    }

    /**
     * 校验用户名
     *
     * @param username
     * @return
     */
    @Override
    public void verifyUserName(String username) {
        //校验用户名不能重复
        List<SysUserEntity> list = this.list(
                new LambdaQueryWrapper<SysUserEntity>()
                        .eq(SysUserEntity::getUsername, username)
        );
        if (list != null && list.size() > 0) {
            throw new RRException(UserException.USERNAME_NOT_REPETITION);
        }
    }

    /**
     * 校验手机号
     *
     * @param mobile
     * @return
     */
    @Override
    public void verifyMobile(String mobile) {
        //校验用户名不能重复
        List<SysUserEntity> list = this.list(
                new LambdaQueryWrapper<SysUserEntity>()
                        .eq(SysUserEntity::getMobile, mobile)
        );
        if (list != null && list.size() > 0) {
            throw new RRException(UserException.MOBILE_NOT_REPETITION);
        }
    }

    /**
     * 校验用户名 和 手机号
     *
     * @param username
     * @return
     */
    @Override
    public void verifyUserName(String username, String mobile) {
        //校验用户名不能重复
        verifyUserName(username);

        //校验手机号不能重复
        verifyMobile(mobile);


    }

    @Override
    public boolean isRelevanceShop(Long[] userIds) {
        return this.baseMapper.isRelevanceShop(userIds);
    }

    @Override
    public SysUserEntity queryByUserNameAndMobile(String username) {
        SysUserEntity sysUserEntity = this.getBaseMapper().selectOne(
                new LambdaQueryWrapper<SysUserEntity>()
                        .eq(SysUserEntity::getUsername, username)
                        .or().eq(SysUserEntity::getMobile, username)
                        .last("limit 1")
        );

        return sysUserEntity;
    }

    @Override
    public boolean isCreateUser(Long[] userIds) {
        return this.baseMapper.isCreateUser(userIds);
    }


}
